/**
 * Created by mango on 2017/3/2.
 */
let fs = require('fs');
let path = require('path');
let build = require('../../bulid');
let template = require('./template');
let index = {

    create: function (document) {

        var summaryPath = build.dirName;
        var fileName = "SUMMARY.md";

        /**
         *解析 document 对象
         * 1 形成 summary
         *
         * 2 创建文件夹
         *
         * 3 形成个 .md 文档
         */

        let summaryContent = [];

        this.getLine(0, document, summaryContent);

        //fs.createWriteStream(path.join(summaryPath, fileName), "utf8");

        let str = summaryContent.join('');
        let temp = path.join(summaryPath, fileName);


        fs.open(temp, "wx+", (error, fd) => {
            fs.writeSync(fd, str, "utf8");
            fs.closeSync(fd);
        });
        // fd.writeSync(fd,summaryContent,'utf8');
        // fd.save();

        // var fileStream = fs.readFileSync(path.join(summaryPath, fileName), "utf8");
        // fileStream.write(summaryContent);
        // fileStream.save();
    },
    getLine: function (level, document, summaryContent) {
        var _this = this;
        document.forEach((item) => {
            if (item.type == "file") {

                summaryContent.push(template.getLine(level, item));
            }
            if (item.type == "dir") {
                summaryContent.push(template.getLine(level, item));
                _this.getLine(level + 1, item.files, summaryContent);
            }

        });
    }
}


module.exports = index;